//
//  BaseViewController.m
//  SafeFoodManagerDemo
//
//  Created by bob on 2017/9/15.
//  Copyright © 2017年 bob. All rights reserved.
//

#import "BaseViewController.h"
#import "LoginViewController.h"
#import "LoginStatuesModel.h"
#import "ImageUploadReq.h"
#import <MWPhotoBrowser/MWPhotoBrowser.h>
#import "AppDelegate+AppService.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "TB_TableView.h"
#import <TZImagePickerController/TZImagePickerController.h>
#import <TZImagePickerController/TZImageManager.h>
#import "UIImage+TB_Scale.h"
#import "ScanPhotoViewController.h"
@interface BaseViewController ()<MWPhotoBrowserDelegate,TZImagePickerControllerDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,POPAnimationDelegate>
{
    NSInteger maxPhotoNum;
    
    BOOL isScanModel;
    
}
//UI控件
@property (nonatomic, strong) UIScrollView *TBScrollViewEmptyDataSet;

/** MJ头部刷新 */
@property (nonatomic, strong) MJRefreshNormalHeader *bsMJRefreshHeader;
/** MJ底部刷新(底部自动刷新) */
@property (nonatomic, strong) MJRefreshAutoNormalFooter *bsMJRefreshFooter;
@property (nonatomic, assign) BOOL isStoreHome;
/**
 相册选择相关
 */
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;

/**
 返回home相关的按钮／调查员开始调查按钮
 */
@property(nonatomic,strong)UIButton *HomeBtn;


@end

@implementation BaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     self.view.backgroundColor=TBColorWhite;
    
     self.StatusBarStyle=UIStatusBarStyleLightContent;
    
    if ([UIDevice systemVersion]<11.0) {
        
        self.automaticallyAdjustsScrollViewInsets=NO;
    }
    // Do any additional setup after loading the view.
}


/**
 动态修改状态栏
 */
- (UIStatusBarStyle)preferredStatusBarStyle{
    return _StatusBarStyle;
}

-(void)setStatusBarStyle:(UIStatusBarStyle)StatusBarStyle{
    _StatusBarStyle=StatusBarStyle;
    [self setNeedsStatusBarAppearanceUpdate];
}


/**
 动态修改键盘toolbar
 */
-(void)setIsHidenKeyToolBar:(BOOL)isHidenKeyToolBar
{
    _isHidenKeyToolBar=isHidenKeyToolBar;
    
    [IQKeyboardManager sharedManager].enableAutoToolbar = !isHidenKeyToolBar;
}


/**
 是否浏览图片

 @param isScanphotos isScanphotos description
 */
-(void)setIsScanphotos:(BOOL)isScanphotos
{
    _isScanphotos=isScanphotos;
    
    if (isScanphotos) {
        
        if (!_ScanPhotoArr) {
            
            _ScanPhotoArr=[NSMutableArray array];
            
        }
    }
}

-(void)setIsHiddenHomeBtn:(BOOL)isHiddenHomeBtn
{
    _isHiddenHomeBtn=isHiddenHomeBtn;
    
    if (_HomeBtn) {
        
     _HomeBtn.hidden=isHiddenHomeBtn;
       
    }
}

/**
 拍照懒加载

 @return pic
 */
- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (iOS9Later) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
        
    }
    return _imagePickerVc;
}


-(UIButton*)HomeBtn
{
    if (!_HomeBtn) {
        
        UIPanGestureRecognizer *recognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                                                     action:@selector(handlePan:)];
        
        _HomeBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        
        _HomeBtn.frame=CGRectMake(self.view.width-80*SCREEN_WIDTH/320.0, self.view.height-80*SCREEN_WIDTH/320.0, 60*SCREEN_WIDTH/320.0, 60*SCREEN_WIDTH/320.0);
        
        _HomeBtn.layer.cornerRadius=60/2.0*SCREEN_WIDTH/320.0;
        
        _HomeBtn.layer.masksToBounds=YES;
        
        [_HomeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
        [_HomeBtn setBackgroundColor:TBColorProvideBtnbg];
       
        [_HomeBtn addTarget:self action:@selector(GotoHome:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.HomeBtn addGestureRecognizer:recognizer];//加手势
        
    }
    return _HomeBtn;
}


#pragma mark - POPAnimationDelegate

- (void)pop_animationDidApply:(POPDecayAnimation *)anim
{
    BOOL isDragViewOutsideOfSuperView = !CGRectContainsRect(self.view.frame, self.HomeBtn.frame);
    if (isDragViewOutsideOfSuperView) {
        CGPoint currentVelocity = [anim.velocity CGPointValue];
        CGPoint velocity = CGPointMake(currentVelocity.x, -currentVelocity.y);
        POPSpringAnimation *positionAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerPosition];
        positionAnimation.velocity = [NSValue valueWithCGPoint:velocity];
        CGFloat space = self.isStoreHome?64:0;
        positionAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(SCREEN_WIDTH-50, SCREEN_HEIGHT-50-space)];
        [self.HomeBtn.layer pop_addAnimation:positionAnimation forKey:@"layerPositionAnimation"];
    }
}

- (void)handlePan:(UIPanGestureRecognizer *)recognizer
{
    CGPoint translation = [recognizer translationInView:self.view];
    recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
                                         recognizer.view.center.y + translation.y);
    [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
    
    if(recognizer.state == UIGestureRecognizerStateEnded) {
        CGPoint velocity = [recognizer velocityInView:self.view];
        POPDecayAnimation *positionAnimation = [POPDecayAnimation animationWithPropertyNamed:kPOPLayerPosition];
        positionAnimation.delegate = self;
        positionAnimation.velocity = [NSValue valueWithCGPoint:velocity];
        [recognizer.view.layer pop_addAnimation:positionAnimation forKey:@"layerPositionAnimation"];
    }
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
}


#pragma mark-登录相关
/**
 是否登陆状态
 */
-(BOOL)isLogin
{
   NSString*Token= [LoginStatuesModel getUserToken];
    
    return Token.length==0?NO:YES;
}

/**
 获取userid
 */

-(NSString*)GetUserid
{
    return [LoginStatuesModel getUserToken];
}

/**
 去登陆
 */

-(void)GotoLoginVC
{
    [LoginStatuesModel CleanUserInfor];
    
    AppDelegate * app = (AppDelegate*)[UIApplication sharedApplication].delegate;
    
    [app initUserManager];
}

/**
 退出登录
 */
-(void)OutLogin
{

    [self showLoadingAnimation];
    
    BaseReqApi *OutApi=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/logout.json" andrequestTime:5 andParams:@{} andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [OutApi StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
       
        [self stopLoadingAnimation];
        
        if (responseStatus==1||responseStatus==404) {
            
            [LoginStatuesModel CleanUserInfor];
            
            AppDelegate * app = (AppDelegate*)[UIApplication sharedApplication].delegate;
            
            [app initUserManager];
            
        }else{
     
            [MBProgressHUD showErrorMessage:message];
            
        }
        
    }];

}

/**
 获取用户类型
 */
-(NSInteger)getUserType
{
    
    return [LoginStatuesModel getUserType];
    
    
}

/**
 返回主页
可重写方法
 @param sender 按钮
 */
-(void)GotoHome:(UIButton*)sender
{
     [sender.layer pop_removeAllAnimations];
    
    [self.navigationController popToRootViewControllerAnimated:YES];
    
}

#pragma mark-加载视图

/**
 *  加载视图
 */
- (void)showLoadingAnimation
{
    
    [MBProgressHUD showActivityMessageInView:@"加载中..." timer:10.0];

}

/**
 *  停止加载
 */
- (void)stopLoadingAnimation
{
    
    [MBProgressHUD hideHUD];
    
}

/**
 *  是否显示返回按钮
 */
- (void) setIsShowLiftBack:(BOOL)isShowLiftBack
{
    _isShowLiftBack = isShowLiftBack;
    
    NSInteger VCCount = self.navigationController.viewControllers.count;
    //下面判断的意义是 当VC所在的导航控制器中的VC个数大于1 或者 是present出来的VC时，才展示返回按钮，其他情况不展示
    if (isShowLiftBack && ( VCCount > 1 || self.navigationController.presentingViewController != nil)) {
        
        [self addNavigationItemWithTitles:@[@" 关闭"] isLeft:YES target:self action:@selector(backBtnClicked) tags:nil];
        
    } else {
        self.navigationItem.hidesBackButton = YES;
        
        UIBarButtonItem * NULLBar=[[UIBarButtonItem alloc]initWithCustomView:[UIView new]];
        self.navigationItem.leftBarButtonItem = NULLBar;
    }
}

#pragma mark-导航栏按钮设置
/**
 导航栏添加文本按钮
 
 @param titles 文本数组
 @param isLeft 是否是左边 非左即右
 @param target 目标
 @param action 点击方法
 @param tags tags数组 回调区分用
 */
- (void)addNavigationItemWithTitles:(NSArray *)titles isLeft:(BOOL)isLeft target:(id)target action:(SEL)action tags:(NSArray *)tags
{
    NSMutableArray * items = [[NSMutableArray alloc] init];
    //调整按钮位置
    UIBarButtonItem* spaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    //将宽度设为负值
    spaceItem.width= -10;
    [items addObject:spaceItem];
    
    NSInteger i = 0;
    for (NSString * title in titles) {
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeSystem];
        btn.frame = CGRectMake(0, 0, 30, 20);
        [btn setTitle:title forState:UIControlStateNormal];
        [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
        btn.titleLabel.font = [UIFont systemFontOfSize:16];
        [btn setTitleColor:TBColorWhite forState:UIControlStateNormal];
        btn.tag = [tags[i++] integerValue];
        [btn sizeToFit];
        UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:btn];
        [items addObject:item];
    }
    if (isLeft) {
        self.navigationItem.leftBarButtonItems = items;
    } else {
        self.navigationItem.rightBarButtonItems = items;
    }
    
}

/**
 导航栏添加图标按钮
 
 @param imageNames 图标数组
 @param isLeft 是否是左边 非左即右
 @param target 目标
 @param action 点击方法
 @param tags tags数组 回调区分用
 */
- (void)addNavigationItemWithImageNames:(NSArray *_Nullable)imageNames isLeft:(BOOL)isLeft target:(id _Nonnull )target action:(SEL _Nonnull )action tags:(NSArray *_Nullable)tags
{
    
    NSMutableArray * items = [[NSMutableArray alloc] init];
    NSInteger i = 0;
    for (NSString * imageName in imageNames) {
        
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    
        [btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
        
        btn.imageView.contentMode = UIViewContentModeScaleAspectFit;
        btn.frame = CGRectMake(0, 0, 30, 30);
        if(isLeft){
            [btn setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 10)];
        }else{
            [btn setImageEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
            
        }
        [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
        
        btn.tag = [tags[i++] integerValue];
        UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:btn];
        [items addObject:item];
        
    }
    if (isLeft) {
        self.navigationItem.leftBarButtonItems = items;
    } else {
        self.navigationItem.rightBarButtonItems = items;
    }
    
}

- (void)addNavigationItemWithImageNames:(NSArray *_Nullable)imageNames Titles:(NSArray *_Nullable)titles isLeft:(BOOL)isLeft target:(id _Nonnull )target action:(SEL _Nonnull )action tags:(NSArray *_Nullable)tags
{
    
    NSMutableArray * items = [[NSMutableArray alloc] init];
    NSInteger i = 0;
    for (NSString * imageName in imageNames) {
        
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
        [btn setTitle:titles[0] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:16];
        
        btn.imageView.contentMode = UIViewContentModeScaleAspectFit;
        btn.frame = CGRectMake(0, 0, 50, 30);
        if(isLeft){
            [btn setImageEdgeInsets:UIEdgeInsetsMake(3, -20, 3, 5)];
            [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, -35, 0, 0)];
        }else{
            [btn setImageEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];

        }
        [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
        
        btn.tag = [tags[i++] integerValue];
        UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:btn];
        [items addObject:item];
        
    }
    if (isLeft) {
        self.navigationItem.leftBarButtonItems = items;
    } else {
        self.navigationItem.rightBarButtonItems = items;
    }
    
}

/**
 导航蓝添加中心视图
 
 @param centView 自定义View
 */
-(void)addCenterView:(UIView*)centView
{
    self.navigationItem.titleView=centView;
    
}

/**
 创建home按钮
 
 @param name 名字
 */
-(void)CreatHomeBtnWithName:(NSString*)name isStoreHome:(BOOL)isStoreHome
{
    self.isStoreHome = isStoreHome;
    [self.view addSubview:self.HomeBtn];
    if(isStoreHome)
    {
        CGFloat iPhoneX =kDevice_Is_iPhoneX?IPhoneXTableHeight:0;

        _HomeBtn.frame=CGRectMake(self.view.width-80*SCREEN_WIDTH/320.0, self.view.height-80*SCREEN_WIDTH/320.0-64-iPhoneX, 60*SCREEN_WIDTH/320.0, 60*SCREEN_WIDTH/320.0);
    }
    [self.HomeBtn setTitle:name forState:UIControlStateNormal];
    
//    [self.HomeBtn sizeToFit];
}

#pragma mark - 没有数据时的提示

/** 配置显示EmptyDataSet的控件 */
- (void)configureNeedShowEmptyDataSetScrollView:(UIScrollView *)scrollView
{
    self.TBScrollViewEmptyDataSet=scrollView;
    
    self.Type=TBNormal;
    
    self.TBScrollViewEmptyDataSet.emptyDataSetSource=self;
    
    self.TBScrollViewEmptyDataSet.emptyDataSetDelegate=self;
    
}

/** 点击EmptyDataSet NoDataView(封装层, 需要子类重写) */
- (void)actionTapEmptyDataSetNodataView
{
    
    
    
    
    
}


#pragma mark - MJ刷新和加载

/**
 配置滚动视图头部刷新 控件
 
 @param scrollView  滚动视图
 @param autoRefresh 是否进入页面就开始刷新
 */
- (void)configScrollViewHeaderRefresh:(UIScrollView *)scrollView autoRefresh:(BOOL)autoRefresh
{
    scrollView.mj_header = self.bsMJRefreshHeader;
    
    if (autoRefresh) {
        
        [scrollView.mj_header beginRefreshing];
    }
}

/**
 配置滚动视图底部加载 控件
 
 @param scrollView 滚动视图
 */
- (void)configScrollViewFooterLoadMore:(UIScrollView *)scrollView
{
    scrollView.mj_footer = self.bsMJRefreshFooter;
    
}


- (MJRefreshNormalHeader *)bsMJRefreshHeader
{
    if (!_bsMJRefreshHeader) {
        _bsMJRefreshHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(actionMJHeaderRefresh)];
        _bsMJRefreshHeader.automaticallyChangeAlpha = YES;
        // 隐藏时间
        _bsMJRefreshHeader.lastUpdatedTimeLabel.hidden = YES;
    }
    return _bsMJRefreshHeader;
}

- (MJRefreshAutoNormalFooter *)bsMJRefreshFooter
{
    if (!_bsMJRefreshFooter) {
        _bsMJRefreshFooter = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(actionMJFooterLoadMore)];
        
        
        _bsMJRefreshFooter.automaticallyHidden = YES;
    }
    return _bsMJRefreshFooter;
}


/**
 *  MJ头部刷新(封装层方法, 需要子类继承或者重写)
 */
- (void)actionMJHeaderRefresh
{
    
    
}

/**
 *  MJ底部加载(封装方法, 需要子类继承或者重写)
 */
- (void)actionMJFooterLoadMore
{
   
    
}




/**
 *  MJ 结束header 和 footer 的刷新
 *
 *  @param scrollView 要停止刷新的 scrollView
 */
- (void)mjEndRefreshing:(UIScrollView *)scrollView
{
    
    if ([scrollView.mj_header isRefreshing]) {
        [scrollView.mj_header endRefreshing];
    }
    if ([scrollView.mj_footer isRefreshing]) {
        [scrollView.mj_footer endRefreshing];
    }
    
}

#pragma mark-网络请求页面显示

/**
 网络请求成功配置
 
 @param vc 当前vc
 @param scrollView 当前tableView
 */
-(void)NetRequestSuccess:(BaseViewController *)vc scrollView:(UIScrollView *)scrollView
{
    [vc mjEndRefreshing:scrollView];
    
    [MBProgressHUD hideHUD];
    
}

/**
 网络请求失败配置
 
 @param vc 当前VC
 @param scrollView 当前tableView
 */
-(void)NetRequestFail:(BaseViewController *)vc scrollView:(UIScrollView *)scrollView msg:(NSString *)msg
{

    [vc mjEndRefreshing:scrollView];
    
    [MBProgressHUD hideHUD];
    
    if (msg) {
        
        [MBProgressHUD showErrorMessage:msg];
    }
    
    if ([scrollView isKindOfClass:[UITableView class]]) {
        UITableView *tableView = (UITableView *)scrollView;
        [tableView reloadData];
    }
    if ([scrollView isKindOfClass:[UICollectionView class]]) {
        UICollectionView *collectionView = (UICollectionView *)scrollView;
        [collectionView reloadData];
    }
}

/**
 *  去上传图片
 */

-(void)UploadPhotosWithImage:(UIImage*)upimage anblock:(PhotoLoadSuccBlock)UploadImgaeblock
{
    NSData *data = UIImageJPEGRepresentation(upimage, 1.0f);
    
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    [MBProgressHUD showActivityMessageInView:@"正在上传..." timer:20];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/uploadImg.json" andrequestTime:20 andParams:@{@"pic":encodedImageStr} andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:NO];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        
        [self stopLoadingAnimation];
        
        if (responseStatus==1) {
            
            [MBProgressHUD showSuccessMessage:@"上传成功"];
            
            UploadImgaeblock(responseObject[@"data"]);
        }else{
            
            [MBProgressHUD showErrorMessage:message];
            
        }
    }];

}

//上传多张图片
-(void)UploadPhotosMoreImage:(NSArray*)upimage anblock:(PhotoLoadSuccBlock)UploadImgaeblock
{
    NSMutableArray *uploadArr=[NSMutableArray array];
    
     [MBProgressHUD showActivityMessageInView:@"正在上传..." timer:20];
    
    for (UIImage *uploadimage in upimage) {
        
        NSData *data = UIImageJPEGRepresentation(uploadimage, 1.0f);
        
        NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/uploadImg.json" andrequestTime:20 andParams:@{@"pic":encodedImageStr} andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:NO];
        
        [uploadArr addObject:api];
    }
    
    YTKBatchRequest *batReq=[[YTKBatchRequest alloc]initWithRequestArray:uploadArr];
    
    [batReq startWithCompletionBlockWithSuccess:^(YTKBatchRequest * _Nonnull batchRequest) {
       
        [self stopLoadingAnimation];
        
        NSArray *requests = batchRequest.requestArray;
    
        NSString*ResultStr=@"";
        
        for (BaseReqApi *Rapi in requests) {
           
            NSLog(@"%@",Rapi.responseObject);
            
            if (ResultStr.length==0) {
                
                ResultStr=Rapi.responseObject[@"data"];
                
            }else{
                
                ResultStr=[NSString stringWithFormat:@"%@|%@",ResultStr,Rapi.responseObject[@"data"]];
            }
       
        }
   
        UploadImgaeblock(ResultStr);
        
         [MBProgressHUD showSuccessMessage:@"上传成功"];
        
    } failure:^(YTKBatchRequest * _Nonnull batchRequest) {
        
        [MBProgressHUD showErrorMessage:@"上传失败"];
        
    }];
    
    
}

#pragma mark-其他
/**
 *  默认返回按钮的点击事件，默认是返回，子类可重写
 */
- (void)backBtnClicked
{
    if (self.presentingViewController) {
        
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }else{
        
        [self.navigationController popViewControllerAnimated:YES];
    }
 
}

//取消网络请求
- (void)cancelRequest
{
    
     [[YTKNetworkAgent sharedAgent]cancelAllRequests];
    
}


- (void)dealloc
{
//    [self cancelRequest];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}


/**
 *  去浏览图片
 */
-(void)GoToPhotoScanAndIndex:(NSInteger)index
{
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = YES;
    browser.displayNavArrows = YES;
    browser.displaySelectionButtons = NO;
    browser.alwaysShowControls = NO;
    browser.zoomPhotosToFill = YES;
    browser.enableGrid = NO;
    browser.startOnGrid = NO;
    browser.enableSwipeToDismiss = NO;
    browser.autoPlayOnAppear = NO;
    
    [browser showNextPhotoAnimated:YES];
    
    [browser showPreviousPhotoAnimated:YES];
    
    [browser setCurrentPhotoIndex:index];
    
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:browser];
    nc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    
    [self presentViewController:nc animated:YES completion:nil];

}

#pragma mark - MWPhotoBrowserDelegate

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    
    return self.ScanPhotoArr.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    
    if (index < self.ScanPhotoArr.count)
        return [self.ScanPhotoArr objectAtIndex:index];
    return nil;
    
}


//自定义标题
- (NSString *)photoBrowser:(MWPhotoBrowser *)photoBrowser
      titleForPhotoAtIndex:(NSUInteger)index {
    return [NSString stringWithFormat:@"%lu/%lu", (unsigned long)index+1,
            (unsigned long)self.ScanPhotoArr.count];
}



/**
 去相册浏览图片
 */
-(void)GotoLibaraySelectPhotoNum:(NSInteger)num andIsCantainScan:(BOOL)scan andBlock:(PhotoShowBlock _Nullable )showImageBlock
{
    _ImageUrlBlock=showImageBlock;
    
    isScanModel=scan;
    
    maxPhotoNum=num;
    
    if (scan) {
        
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"去相册选择",@"扫一扫", nil];
        [sheet showInView:self.view];
        
    }else{
    
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"去相册选择", nil];
    [sheet showInView:self.view];
    
    }
}

#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) { // take photo / 去拍照
        if ([[TB_Permiss sharePermiss] CameraAuthority]) {
            
            [self takePhoto];
            
        }
    } else if (buttonIndex == 1) {
        if ([[TB_Permiss sharePermiss] PhotoLibraryAuthority]) {
            
            [self pushTZImagePickerController];
        }
        
    }else if (buttonIndex==2)
    {
        
        if (isScanModel) {
            
               if ([[TB_Permiss sharePermiss] CameraAuthority]) {
            //扫一扫
            ScanPhotoViewController*scanVC=[ScanPhotoViewController new];
            
            scanVC.Scantype=1;
            
            scanVC.resultBlock=^(NSString *Str)
            {
                _ImageUrlBlock(Str);
                
            };
            
            [self.navigationController pushViewController:scanVC animated:YES];
            
               }
        }
        
        
    }
}

#pragma mark-去相册选择
-(void)pushTZImagePickerController{
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:maxPhotoNum columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    
    imagePickerVc.allowPickingVideo=NO;
    
    imagePickerVc.allowTakePicture=NO;

    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        if (maxPhotoNum==1) {
            
            UIImage *image=photos[0];
            
            if (isSelectOriginalPhoto) {
                
                if (image.size.width>500) {
                    
                    image=[image thumbnailWithImageWithoutScale:image size:CGSizeMake(500, 500*image.size.height/image.size.width)];
                }
                
            }
            
            //此处需上传图片:
            [self UploadPhotosWithImage:image anblock:^(NSString *imagStr) {
                
                _ImageUrlBlock(imagStr);
                
            }];
            
        }else{
            
            //批量上传
   
            [self UploadPhotosMoreImage:photos anblock:^(NSString * MoreimageStr) {
               
                _ImageUrlBlock(MoreimageStr);
                
            }];
   
        }
 
        
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    
}

#pragma mark-去拍照
-(void)takePhoto
{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) && iOS7Later) {
        // 无相机权限 做一个友好的提示
        if (iOS8Later) {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
            [alert show];
        } else {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        }
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        if (iOS7Later) {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        [self takePhoto];
                    });
                }
            }];
        } else {
            [self takePhoto];
        }
        // 拍照之前还需要检查相册权限
    } else if ([TZImageManager authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        if (iOS8Later) {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
            [alert show];
        } else {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        }
    } else if ([TZImageManager authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
        [self pushImagePickerController];
    }
 
    
}

#pragma mark-拍照
-(void)pushImagePickerController
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerVc.sourceType = sourceType;
        if(iOS8Later) {
            _imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        }
        [self presentViewController:_imagePickerVc animated:YES completion:nil];
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
    
}


- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
        tzImagePickerVc.sortAscendingByModificationDate = YES;
        [tzImagePickerVc showProgressHUD];
        
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        //此处需上传图片:
        [self UploadPhotosWithImage:[image thumbnailWithImageWithoutScale:image size:CGSizeMake(500, image.size.height*500/image.size.width)] anblock:^(NSString *imagStr) {
            
            _ImageUrlBlock(imagStr);
            
        }];
        // save photo and get asset / 保存图片，获取到asset
        [[TZImageManager manager] savePhotoWithImage:image location:nil completion:^(NSError *error){
            if (error) {
                [tzImagePickerVc hideProgressHUD];
                NSLog(@"图片保存失败 %@",error);
            }
        }];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    
      [picker dismissViewControllerAnimated:YES completion:nil];
    
}

#pragma mark -  屏幕旋转
-(UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    //当前支持的旋转类型
    return UIInterfaceOrientationMaskPortrait;
}

- (BOOL)shouldAutorotate
{
    // 是否支持旋转
    return NO;
}

-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    // 默认进去类型
    return   UIInterfaceOrientationPortrait;
}


#pragma mark-DZNEmptyDataSetSource


//空白页内容
-(void)setType:(TBBlanckType)Type
{
    _Type=Type;
    
    [self.TBScrollViewEmptyDataSet reloadEmptyDataSet];
}


- (void)emptyDataSetWillAppear:(UIScrollView *)scrollView {
    scrollView.contentOffset = CGPointZero;
}

//空白页图片
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    if (self.Type==TBReqLoading) {
        
        return [UIImage imageNamed:@"loading_imgBlue_78x78"];
        
    }else if (self.Type==TBNODateType){
        
        return [UIImage imageNamed:@"emptynoData"];
        
    }else if (self.Type==TBSearchNoType){
        
        return [UIImage imageNamed:@"placeholder_appstore"];
        
    }else if (self.Type==TBNormal){
        
        return nil;
        
    }else if (self.Type==HBselectShop){
        return [UIImage imageNamed:@"emptynoData"];
    } else {
        
        return [UIImage imageNamed:@"placeholder_remote"];
    }
    
}

//空白页动画效果
- (CAAnimation *)imageAnimationForEmptyDataSet:(UIScrollView *)scrollView {
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath: @"transform"];
    
    animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
    animation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeRotation(M_PI_2, 0.0, 0.0, 1.0)];
    
    animation.duration = 0.25;
    animation.cumulative = YES;
    animation.repeatCount = MAXFLOAT;
    
    return animation;
}



//标题文本，详细描述，富文本样式
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    
    
    NSString *text = @"";
    
    if (self.Type==TBNODateType) {
        
        text=@"没有任何数据";
        
    }else if (self.Type==TBSearchNoType){
        
        text=@"没有搜到你要的内容，换个词语试试吧";
        
    }else if(self.Type==TBReqFalie) {
        
        text=@"网络开小差了!";
    }else if (self.Type==HBselectShop)
    {
        text=@"请选择商品";
    }
    
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:28.0f],
                                 NSForegroundColorAttributeName: [UIColor darkGrayColor]};
    if(self.Type==HBselectShop)
    {
        attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:28.0f],
                       NSForegroundColorAttributeName: TBColorProvideBtnbg};
    }
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}



//按钮文本
- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state {
    
    if (self.Type==TBReqFalie||self.Type==TBReqLoading) {
        
        NSString *showtip=nil;
        
        if (self.Type==TBReqLoading) {
            
            showtip=@"正在重试";
            
        }else if (self.Type==HBselectShop)
        {
            showtip=@"选择商品";
        }
        else{
            
            showtip=@"点击重试";
            
        }
        
        NSDictionary *attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:26.0f],NSForegroundColorAttributeName:TBColorProvideBtnbg};
        
        return [[NSAttributedString alloc] initWithString:showtip attributes:attributes];
        
    }else{
        
        return nil;
        
    }
    
}

- (CGFloat)spaceHeightForEmptyDataSet:(UIScrollView *)scrollView
{
    
    return 40;
    
}


//空白页背景色
- (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIColor whiteColor];
}

#pragma mark-DZNEmptyDataSetDelegate

//是否显示空白页，默认YES
- (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView {
    return YES;
}

//是否允许点击，默认YES
- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView {
    return YES;
}

//是否允许滚动，默认NO
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

//图片是否要动画效果，默认NO
- (BOOL)emptyDataSetShouldAnimateImageView:(UIScrollView *)scrollView {
    
    if (self.Type==TBReqLoading) {
        
        return YES;
    }
    
    return NO;
}

//空白页点击事件
- (void)emptyDataSetDidTapView:(UIScrollView *)scrollView {
    
    if (self.Type==TBReqFalie) {
        
        self.Type=TBReqLoading;
        
        [self actionTapEmptyDataSetNodataView];
    }else if (self.Type==HBselectShop)
    {
        [self actionTapEmptyDataSetNodataView];
    }
    
}

//空白页按钮点击事件
- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button{
    
    if (self.Type==TBReqFalie) {
        
        self.Type=TBReqLoading;
        
        [self actionTapEmptyDataSetNodataView];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
